package com.carl.mall.controller;


import com.alibaba.fastjson.JSON;
import com.carl.common.constant.AuthConstant;
import com.carl.common.utils.HttpUtils;
import com.carl.common.utils.R;
import com.carl.common.vo.MemberVO;
import com.carl.mall.feign.MemberFeignService;
import com.carl.mall.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


/**
 * 微博认证控制器
 */
@Controller
public class OAuth2Controller {


    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 微博认证服务需调用该接口
     * @param code
     * @return
     * @throws Exception
     */
    @RequestMapping("/oauth/weibo/success")
    public String weiboOAuth(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String,String> body = new HashMap<>();
        body.put("client_id","");
        body.put("client_secret","");
        body.put("grant_type","authorization_code");
        body.put("redirect_uri","http://auth.carl.com/oauth/weibo/success");
        body.put("code",code);
        //根据Code获取对应的Token信息
        HttpResponse post = HttpUtils.doPost("https://api.weibo.com"
                , "/oauth2/access_token"
                , "post"
                , new HashMap<>()
                , null
                , body
        );
        int statusCode = post.getStatusLine().getStatusCode();
        if (statusCode != 200){
            // 说明获取Token失败,就调回到登录页面
            return "redirect:http://auth.carl.com/login.html";
        }
        //说明获取Token信息成功
        String json = EntityUtils.toString(post.getEntity());
        SocialUser socialUser = JSON.parseObject(json,SocialUser.class);
        if (!StringUtils.isEmpty(socialUser)){
            R r = memberFeignService.socialLogin(socialUser);
            if (r.getCode() != 0){
                return "redirect:http://auth.carl.com/login.html";
            }
            //单纯想拿到这个entity 没别的意思
            //获取用户的全量信息
            String entityJson = (String) r.get("entity");
            MemberVO memberVO = JSON.parseObject(entityJson, MemberVO.class);
            session.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberVO);
        }
        return "redirect:http://auth.carl.com/home";
    }
}
